import React, { useMemo, useRef } from 'react';
import { withRouter } from 'umi';
import { PageContainer } from '@/molecules';
import EmployeeCardSimple from '@/pages/Organization/EmployeeManage/components/EmployeeCard/EmployeeCardSimple';
import { defaultFormatResult, useRequest } from '@/hooks';
import { getLeaderHistory, queryEmployeeArchiveHead } from '@/pages/Organization/EmployeeManage/services';
import { Button, Divider, Empty, Skeleton, Table, Tooltip, Tag, message } from 'antd';
import moment from 'moment';
import AuthComponent from '@/utils/auth/AuthComponent';
import { createDictionary } from '@/dictionary';
import { history } from 'umi';
import IconFont from '@/components/IconFont';
import styles from './index.less';

const [, getSupervisorStatusText] = createDictionary('SUPERVISOR_STATUS');

/**
 * 主管履历
 */
const EmployeeSupervisor = props => {
    const { location } = props;
    const { employeeCode } = location.query;
    const employeeInfoCardRef = useRef();
    // const [loading, setLoading] = useState(false);
    // 获取数据
    const { data: supervisorData, loading: supervisorLoading } = useRequest(() => getLeaderHistory(employeeCode), {
        ready: employeeCode,
        refreshDeps: [employeeCode],
        ...defaultFormatResult
    });
     // 用户数据
    const {
        data: employeeInfoData,
        loading: employeeInfoLoading
    } = useRequest(() => queryEmployeeArchiveHead({ employeeCode }), {
        ...defaultFormatResult
    });

    // 添加主管机构
    const handleAdd = () => {
        history.push({
            pathname: '/office/personnelManagement/organization/orgflow/supervisorSet',
            query: {
                // organizationCode: employeeInfoCardRef.current?.data?.organizationCode,
                employeeCode,
                entranceSign: 'personnel'
            }
        });
    };

    // const handleDelete = useMemo(
    //     () => async record => {
    //         // 校验流程是否存在
    //         setLoading(true);
    //         const { workFlowUrl } = await hasWorkFlowByType('LeaderSettingApply');
    //         if (workFlowUrl) {
    //             const { titleName, titleValue, ...res } = record;
    //             const param = {
    //                 ...res,
    //                 titleName: res.leaderDutyAlias,
    //                 titleValue: res.leaderDutyCode
    //             };
    //             const { msg, code, data: id } = await deleteLeader(param);
    //             if (code === 10000) {
    //                 // await eventTrack({
    //                 //     eventName: 'todo',
    //                 //     eventProps: {}
    //                 // });
    //                 history.push(`${workFlowUrl}${id}`);
    //             } else {
    //                 // eventTrack({
    //                 //     eventName: 'todo',
    //                 //     eventProps: {}
    //                 // });
    //                 message.error(msg);
    //             }
    //         }
    //         setLoading(false);
    //     },
    //     []
    // );

    const columns = useMemo(
        () => [
            {
                title: '管理机构',
                dataIndex: 'organizationName',
                key: 'organizationName',
                align: 'center',
                render: text => text || '--'
            },
            {
                title: '岗位',
                dataIndex: 'leaderDutyAlias',
                key: 'leaderDutyAlias',
                // align: 'center',
                render: (text, record) => (
                    <>
                        {text}
                        {record?.dutyType === 0 ? (
                            <Tag color="blue" style={{ marginLeft: 8 }}>
                                兼任
                            </Tag>
                        ) : (
                            ''
                        )}
                    </>
                )
            },
            {
                title: '员工',
                dataIndex: 'organizationStaffNum',
                key: 'organizationStaffNum',
                align: 'center',
                render: text => (text === 0 ? text : text ?? '--')
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: text => (
                    <span style={Number(text) === 1 ? { color: '#FFA22D' } : {}}>{getSupervisorStatusText(text)}</span>
                )
            },
            {
                title: '任命人',
                dataIndex: 'appointEmployeeName',
                key: 'appointEmployeeName',
                align: 'center',
                render: text => text || '--'
            },
            {
                title: '任命时间',
                dataIndex: 'appointTime',
                key: 'appointTime',
                render: text => (text ? moment(text).format('YYYY-MM-DD') : '--')
            },
            {
                title: '卸任时间',
                dataIndex: 'leaveTime',
                key: 'leaveTime',
                render: text => (text ? moment(text).format('YYYY-MM-DD') : '--')
            },
            {
                title: '操作',
                dataIndex: 'operation',
                key: 'operation',
                align: 'center',
                width: 170,
                render: (text, record) => (
                    <>
                        {/* <AuthComponent code="office:orgs:employee:leaderInfo:detail"> */}
                        <Tooltip title="查看审批详情">
                            <IconFont
                                isButton
                                style={{
                                    fontSize: '20px',
                                    verticalAlign: 'middle'
                                }}
                                icon="iconchakanxiangqing"
                                onClick={() =>
                                    history.push({
                                        pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                        query: { applicationNo: record.applicationNo },
                                        state: { tabRoute: true, tabRefresh: true }
                                    })
                                }
                            />
                        </Tooltip>
                        <Divider type="vertical" />
                        {/* </AuthComponent> */}
                        {/* <AuthComponent code="office:orgs:employee:leaderInfo:editLeader">
                            <Tooltip placement="top" title="修改">
                                <IconFont
                                    disabled={record.status !== 2}
                                    style={{ verticalAlign: 'middle' }}
                                    onClick={() =>
                                        history.push({
                                            pathname: '/office/personnelManagement/organization/orgflow/supervisorEdit',
                                            query: {
                                                organizationCode: record.organizationCode,
                                                organizationName: record.organizationName,
                                                employeeCode: record.employeeCode,
                                                entranceSign: 'personnel'
                                            }
                                        })
                                    }
                                    icon="iconlistfunction_edit_icon_default"
                                    isButton
                                />
                            </Tooltip>
                            <Divider type="vertical" />
                        </AuthComponent> */}
                        <AuthComponent code="office:orgs:employee:leaderInfo:leave">
                            {/* <Popconfirm title="你确定删除吗?" onConfirm={} okText="确定" cancelText="取消" > </Popconfirm> */}
                            <Tooltip placement="top" title="卸任主管">
                                <IconFont
                                    disabled={record.status !== 2}
                                    style={{ verticalAlign: 'middle' }}
                                    icon="iconlistfunction_delete_icon_default"
                                    isButton
                                    onClick={() => {
                                        if (record?.dutyType === 1) {
                                            message.warn({
                                                content: '该主管岗位是主岗不能直接卸任，请后续走调岗流程！',
                                                duration: 4
                                            });
                                        } else {
                                            history.push({
                                                pathname:
                                                    '/office/personnelManagement/organization/orgflow/supervisorEdit',
                                                query: {
                                                    organizationCode: record?.organizationCode,
                                                    employeeCode: record?.employeeCode,
                                                    entranceSign: 'leave'
                                                },
                                                state: { tabRoute: true, tabRefresh: true }
                                            });
                                        }
                                    }}
                                />
                            </Tooltip>
                        </AuthComponent>
                    </>
                )
            }
        ],
        []
    );

    return (
        <PageContainer>
            <EmployeeCardSimple ref={employeeInfoCardRef} employeeCode={employeeCode} />
            {employeeCode && (
                <>
                    <Divider style={{ margin: '16px 0' }} />
                    <Skeleton loading={supervisorLoading || employeeInfoLoading}>
                        {supervisorData?.length ? (
                            <>
                                <Table
                                    loading={supervisorLoading}
                                    rowKey="id"
                                    columns={columns}
                                    dataSource={supervisorData}
                                    pagination={false}
                                />
                                {employeeInfoData?.serviceStatus !== 6 &&
                                    <AuthComponent code="office:orgs:employee:leaderInfo:setLeader">
                                        <Button
                                            type="dashed"
                                            icon="plus"
                                            onClick={handleAdd}
                                            style={{ marginTop: 20, width: '100%' }}
                                        >
                                            添加主管机构
                                        </Button>
                                    </AuthComponent>
                                }
                            </>
                        ) : (
                            <div className={styles.notFound}>
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无主管信息" />
                                {employeeInfoData?.serviceStatus !== 6 &&
                                    <AuthComponent code="office:orgs:employee:leaderInfo:setLeader">
                                        <Button type="primary" icon="plus" onClick={handleAdd}>
                                            添加主管机构
                                        </Button>
                                    </AuthComponent>
                                }
                            </div>
                        )}
                    </Skeleton>
                </>
            )}
        </PageContainer>
    );
};

EmployeeSupervisor.displayName = 'EmployeeSupervisor';

export default withRouter(EmployeeSupervisor);
